<?php
/**
 * Created by JetBrains PhpStorm.
 * User: scala
 * Date: 12-10-26
 * Time: 上午9:30
 * To change this template use File | Settings | File Templates.
 */
class PublicAction extends Action
{

    function login(){
        $this->display();
    }

    function checkLogin(){
        header("Content-Type:text/html; charset=utf-8");
        import("ORG.Util.Session");
        $verifycode=trim($_POST["verifycode"]);
        if(empty($verifycode)){
            $this->ajaxReturn("","请输入验证码!",0);
        }
        if($_SESSION["verify"]==md5($verifycode)){
            if(!empty($_POST["username"])&&!empty($_POST["password"])){
                //生成认证条件
                $map['username']	= $_POST['username'];
                $map["status"]	=	array('eq',1);
                import ( 'ORG.Util.RBAC' );
                $authInfo = RBAC::authenticate($map);
                if(false === $authInfo||null===$authInfo) {
                    $this->ajaxReturn("","用户不存在或者是用户未激活!",0);
                }else {
                    if($authInfo['password'] != md5($_POST['password'])) {
                        $this->ajaxReturn("","密码输入有误!",0);
                    }else{
                        Session::set(C('USER_AUTH_KEY'),$authInfo['id']);
                        Session::set("nickname",$authInfo["nickname"]);
                        if(C("ENABLE_ADMIN_AUTH_KEY")){
                            if($authInfo['username']=='admin') {//设置超级管理员为admin
                                $_SESSION[C("ADMIN_AUTH_KEY")]		=	true;
                            }
                        }
                        //保存登录信息
                        $User	=	M('User');
                        $ip		=	get_client_ip();
                        $time	=	time();
                        $data['id']	=	$authInfo['id'];
                        $data['last_login_time']	=	$time;
                        $data['login_count']	=	array('exp','login_count+1');
                        $data['last_login_ip']	=	$ip;
                        $User->save($data);

                        // 缓存访问权限
                        RBAC::saveAccessList();
                        $this->ajaxReturn("Index/index","登录成功!",2);
                    }

                }
            }else{
                $this->ajaxReturn("","登录失败，请输入用户名密码然后登录!",0);
            }
        }else{
            $this->ajaxReturn("","验证码不正确!",0);
        }
    }

    function logout(){
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION);
            session_destroy();
            $this->redirect("Public/login");
        }else {
            $this->redirect("Public/login");
        }
    }

    /**
     * 生成验证码
     */
    function verify(){
        header("Content-Type:text/html; charset=utf-8");
        import("ORG.Util.Image");
        Image::buildImageVerify();
    }
}
